package com.tj.jinzao.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.widget.LinearLayoutManager;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.tj.jinzao.R;
import com.tj.jinzao.adapter.ImageListItemAdapter;
import com.tj.jinzao.base.BaseActivity;
import com.tj.jinzao.base.ConstantApp;
import com.tj.jinzao.base.RecyclerViewGridAdapter;
import com.tj.jinzao.callback.IUploadView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.model.Target;
import com.tj.jinzao.presenter.PublicArticlePresenter;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.utils.Utils;
import com.tj.jinzao.widgets.MaxTextLengthFilter;
import com.tj.jinzao.widgets.MyRecyclerView;
import com.tj.jinzao.widgets.PictureDialog;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import butterknife.BindView;

import static com.luck.picture.lib.config.PictureConfig.CHOOSE_REQUEST;

/**
 * 发布日记
 * Created by wjy on 2019/1/12.
 */
public class PublicDailyActivity extends BaseActivity<PublicArticlePresenter> implements IUploadView<String> {

    @BindView(R.id.my_list)
    MyRecyclerView mRecycleView;
    @BindView(R.id.et_content)
    EditText mContentView;
    private CopyOnWriteArrayList<String> mImgList;
    private ImageListItemAdapter mButtonAdapter;
    private int mItemWidth;
    private String mImages;
    private String mVideoPath;

    private static final int IMAGE_SIZE = 5;
    private static final int VIDEO_SIZE = 1;

    private boolean mChooseVideo;

    @Override
    protected PublicArticlePresenter createPresenter() {
        return new PublicArticlePresenter(this);
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_public_daily;
    }

    @Override
    protected int getLeftButtonResId() {
        return R.mipmap.ic_back;
    }

    @Override
    public void onBackPressed() {
        clickLeftButton();
    }

    @Override
    protected CharSequence getRightButtonText() {
        return "发布";
    }

    @Override
    protected void clickRightButton() {
        checkResource();
    }

    @Override
    protected void setupView() {
        mPresenter = new PublicArticlePresenter(this);
        mImgList = new CopyOnWriteArrayList();
        mImgList.add("0");
        int leftMargin = Utils.dpToPx(16, getResources());
        int leftpadding = Utils.dpToPx(2, getResources());
        mItemWidth = (Constant.SCREEN_WIDTH - leftMargin * 2 - leftpadding * 3) / 4;
        mRecycleView.setLayoutManager(new LinearLayoutManager(this));
        mButtonAdapter = new ImageListItemAdapter(this, mImgList, mItemWidth);
        mButtonAdapter.setOnItemClickListener(new ImageListItemAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, boolean isDelete) {
                if (isDelete) {
                    mImgList.remove(position);
                    if (mChooseVideo) {
                        mChooseVideo = false;
                        if (mImgList.size() == 0) {
                            mImgList.add("0");
                        }
                    } else if (mImgList.size() < IMAGE_SIZE) {
                        if (!mImgList.contains("0")) mImgList.add("0");
                    }
                    mRecycleView.getAdapter().notifyDataSetChanged();
                } else if (TextUtils.equals(mImgList.get(position), "0")) {
                    PictureDialog dialog = new PictureDialog(PublicDailyActivity.this);
                    dialog.setMaxNumber(5);
                    if (mChooseVideo) dialog.setHideImage(true);
                    else if (mImgList.size() > 1) dialog.setHideVideo(true);
                    dialog.show();
                } else {

                }

            }
        });
        RecyclerViewGridAdapter adapter = new RecyclerViewGridAdapter(this, 4, mButtonAdapter);
        adapter.setItemSize(mItemWidth, mItemWidth);
        adapter.setMargin(leftMargin, leftMargin, 0, leftMargin, leftpadding);
        mRecycleView.setAdapter(adapter);

    }


    private void checkResource() {
        String content = mContentView.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            ToastUtils.showToast(this, "请写点内容吧");
            return;
        } else if (checkUploadResource()) {
            if(ConstantApp.isFastDoubleClick(1500)){
                return;
            }
            mPresenter.publicDaily(content, mImages, mChooseVideo, mVideoPath);
        }
    }

    /**
     * 循环检测发送资源是否已经上传
     */
    public boolean checkUploadResource() {
        mImages = "";
        Log.w("数据接收图片上传","aaa"+mImgList.toString());
        if (mImgList != null && mImgList.size() > 0) {
            StringBuilder imageUrls = null;
            for (String path : mImgList) {

                if (TextUtils.equals(path, "0")) {
                    continue;
                }
                if (path.startsWith(Constant.SD_ROOT)) {
                    mPresenter.uploadFile(path);
                    return false;
                } else {
                    if (imageUrls == null) imageUrls = new StringBuilder();
                    else imageUrls.append(",");
                    imageUrls.append(path);
                }
            }
            mImages = imageUrls == null ? "" : imageUrls.toString();

        }
        if (mChooseVideo) {
            if (mVideoPath.startsWith(Constant.SD_ROOT)) {
                mPresenter.uploadFile(mVideoPath);
                return false;
            }
        }
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 结果码不等于取消时候
        if (resultCode != Activity.RESULT_CANCELED) {
            switch (requestCode) {
                case CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    for (LocalMedia localMedia : selectList) {
                        mChooseVideo = localMedia.getPictureType().startsWith("video");
                        String path = localMedia.isCompressed() ? localMedia.getCompressPath() : localMedia.getPath();
                        if (mChooseVideo) {
                            mVideoPath = path;
                            Bitmap bitmap = Utils.getVideoThumb(path);
                            path = Constant.SD_TEMP_IMAGE + System.currentTimeMillis() + ".jpg";
                            Utils.saveBitmap(path, bitmap);
                        }
                        setData(path);
                    }
                    break;
            }
        }
    }


    /**
     * 保存裁剪之后的图片数据
     */
    private void setData(String filePath) {
        if (mChooseVideo) {
            if (mImgList.size() < VIDEO_SIZE + 1) {
                mImgList.clear();
                mImgList.add(filePath);
            }
        } else {
            if (mImgList.size() < IMAGE_SIZE + 1) {
                mImgList.add(mImgList.size() - 1, filePath);
                if (mImgList.size() == IMAGE_SIZE + 1 && mImgList.contains("0")) {
                    mImgList.remove("0");
                }
            }
        }
        mRecycleView.getAdapter().notifyDataSetChanged();
    }

    /**
     * 返回时弹出是否放弃编辑弹框
     */

    @Override
    public Activity getContext() {
        return this;
    }

    @Override
    public void onRequestSuccess(String s) {

    }

    @Override
    public void onRequestNoData(String message) {

    }

    @Override
    public void onRequestError(String error_message) {

    }

    @Override
    public void onUploadSuccess(String path, String url) {
        if (mImgList != null) {
            for (int i = 0; i < mImgList.size(); i++) {
                if (TextUtils.equals(mImgList.get(i), path)) {
                    mImgList.set(i, url);
                    break;
                }
            }
            if (TextUtils.equals(mVideoPath, path)) {
                mVideoPath = url;
            }
            checkResource();
        }
    }

    @Override
    public void onCaseSuccess(List<Target> list) {

    }

    @Override
    public void onCaseFailed(String msg) {

    }
}
